package com.zscat.mallplus.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zscat.mallplus.annotation.IgnoreAuth;
import com.zscat.mallplus.core.LockInfo;
import com.zscat.mallplus.dms.entity.DmsOrder;
import com.zscat.mallplus.dms.service.*;
import com.zscat.mallplus.enums.OrderStatus;
import com.zscat.mallplus.enums.RoomStatus;
import com.zscat.mallplus.enums.TaskType;
import com.zscat.mallplus.qsg.*;
import com.zscat.mallplus.qsg.impl.MqttConfigService;
import com.zscat.mallplus.ums.entity.UmsMember;
import com.zscat.mallplus.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 设备管理Controller
 */
@RestController
@Api(tags = "QsgTaskController", description = "任务管理")
@RequestMapping("/api/dms")
@Slf4j
public class QsgTaskController {

    @Autowired
    private IDeviceTaskService taskService;
    @Autowired
    private IDmsOrderService orderService;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IMealService mealService;
    @Autowired
    private IRoomService roomService;
    @Autowired
    private MqttConfigService mqttConfigService;

    @Autowired
    private IGatewayDeviceService gatewayDeviceService;

    @Autowired
    private IQsgGatewayInfoService gatewayInfoService;

    @IgnoreAuth
    @GetMapping(value = "/task/generateBaoxiang")
    @ApiOperation(value = "生成包厢门任务")
    public Object generateBaoxiang(@RequestParam(required = false) Long orderId) {
        Date now = new Date();
        UmsMember currentMember = UserUtils.getCurrentMember();
        List<DmsOrder> orders = null;
        if (null == orderId) {
            //首页点击开包厢门
            QueryWrapper qw = new QueryWrapper();
            qw.eq("member_id", currentMember.getId());
            qw.eq("order_status", 2);
            qw.le("start_time", DateUtil.dateToStr(new Date(), "yyyy/MM/dd HH:mm"));
            orders = orderService.list(qw);
            if (null == orders || orders.size() <= 0) {
                return new CommonResult().success(1);
            }
        } else {
            DmsOrder order = orderService.getById(orderId);
            orders = new ArrayList<>();
            orders.add(order);
        }
        for (DmsOrder order : orders) {
            Long deviceId = order.getDeviceId();
            QsgDevice device = deviceService.getById(deviceId);
            if (device.getIsGateway().intValue() == 0) {
                //网关设备房间
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("device_id", device.getId());
                queryWrapper.eq("is_voice", 0);
                order.setOpenStatus(1);
                orderService.updateById(order);
                QueryWrapper timeQw = new QueryWrapper();
                timeQw.eq("order_sn", order.getOrderSn());
                timeQw.eq("device_id", device.getId());
                List<QsgDeviceTask> tasks = taskService.list(timeQw);
                if (null == tasks || tasks.size() == 0) {
                    //没有该笔订单生成的时间任务，则生成
                    QsgDeviceTask timeTask = new QsgDeviceTask();
                    timeTask.setUpdateReason("网关点击开门生成");
                    timeTask.setUpdateTime(new Date());
                    timeTask.setMemberId(currentMember.getId().intValue());
                    timeTask.setCreateDatetime(new Date());
                    timeTask.setDeviceId(device.getId());
                    timeTask.setDeviceCode(device.getDeviceCode());
                    timeTask.setOrderSn(order.getOrderSn());
                    String endTime = order.getEndTime();
                    Date date = new Date(endTime);
                    timeTask.setEndTime(date);
                    timeTask.setTaskType(TaskType.GATEWAY_END_REPORT.getValue());
                    taskService.save(timeTask);//结束任务
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(date);
                    calendar.add(Calendar.MINUTE, -10);
                    timeTask.setEndTime(calendar.getTime());
                    timeTask.setTaskType(TaskType.GATEWAY_TEN_REPORT.getValue());
                    taskService.save(timeTask);//结束前10分钟
//                    Calendar current = Calendar.getInstance();
//                    current.add(Calendar.SECOND, 30);
//                    timeTask.setEndTime(current.getTime());
//                    timeTask.setTaskType(TaskType.GATEWAY_DELAY_CLOSEDOOR_REPORT.getValue());
//                    taskService.save(timeTask);//延迟30秒关门任务
                }
                List<QsgGatewayDevice> gatewayDevices = gatewayDeviceService.list(queryWrapper);
                if (gatewayDevices.size() > 0) {
                    try {
                        for (QsgGatewayDevice gatewayDevice : gatewayDevices) {
                            QsgGatewayInfo gatewayInfo = gatewayInfoService.getById(gatewayDevice.getGatewayId());
                            if (device.getDeviceType().intValue() == 2) {
                                //使用的WiFi锁
                                sendWifiLockMsg(device);
                                operateGatewayDeivce(gatewayDevice, gatewayInfo, 0);
                            } else if (device.getDeviceType().intValue() == 3) {
                                //谷家锁
                                JSONObject data = new JSONObject();
                                data.put("CommandId", UUID.randomUUID().toString());
                                data.put("SystemCode", "csqsg");
                                data.put("GatewayIeee", gatewayInfo.getSerialno());
                                data.put("SensorIeee", device.getDeviceCode());
                                data.put("Command", "UnlockDoor");
                                data.put("PINCode", "1809598");
                                mqttConfigService.publish("/toGW/" + gatewayInfo.getMacAddr(), data.toJSONString());
                                operateGatewayDeivce(gatewayDevice, gatewayInfo, 0);
                            } else {
                                //磁吸锁
                                operateGatewayDeivce(gatewayDevice, gatewayInfo, 0);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            if (device.getDeviceType().intValue() == 1) {
                //新设备
                try {
//                    if (order.getOpenStatus()==0){
                    //还没有开启过的，需要生成任务，新设备即需要发送订单指令
                    JSONObject data1 = new JSONObject();
                    JSONObject header1 = new JSONObject();
                    JSONObject body1 = new JSONObject();
                    header1.put("Code", "1004");
                    header1.put("Time", System.currentTimeMillis());
                    header1.put("Sign", "lvzaina");
                    data1.put("Header", header1);
                    QueryWrapper queryWrapper = new QueryWrapper();
                    queryWrapper.eq("start_time", order.getEndTime());
                    queryWrapper.eq("order_status", 2);
                    queryWrapper.eq("member_id", order.getMemberId());
                    queryWrapper.eq("device_id", order.getDeviceId());
                    DmsOrder xudingOrder = orderService.getOne(queryWrapper);
                    int time = 0;
                    if (null != xudingOrder) {
                        time = DateUtil.differentSecondByMillisecond(new Date(xudingOrder.getEndTime()), new Date());
                    } else {
                        time = DateUtil.differentSecondByMillisecond(new Date(order.getEndTime()), new Date());
                    }
                    body1.put("Delay", time);
                    body1.put("Cmd", "Order");
                    body1.put("MsgId", 1683557943);
                    body1.put("Lock", 0);
                    body1.put("Type", 0);
                    body1.put("ID", 0);
                    JSONArray node = new JSONArray();
                    node.add(1);
                    node.add(2);
                    body1.put("Node", node);
                    data1.put("Body", body1);
                    mqttConfigService.publish("topic/receive/" + device.getDeviceCode(), data1.toJSONString());
                    order.setOpenStatus(1);
                    orderService.updateById(order);
                    Timer timer = new Timer();
                    TimerTask timerTask = new TimerTask() {
                        @Override
                        public void run() {
                            try {
                                JSONObject data = new JSONObject();
                                JSONObject header = new JSONObject();
                                JSONObject body = new JSONObject();
                                header.put("Code", "1004");
                                header.put("Time", System.currentTimeMillis());
                                header.put("Sign", "lvzaina");
                                data.put("Header", header);
                                body.put("Delay", 3);
                                body.put("Cmd", "RemoteOpenDoor");
                                body.put("MsgId", 1682220193);
                                body.put("Lock", 189);
                                body.put("Type", 0);
                                body.put("ID", 0);
                                data.put("Body", body);
                                mqttConfigService.publish("topic/receive/" + device.getDeviceCode(), data.toJSONString());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    };
                    timer.schedule(timerTask,2000);
//                    }else {
//                        JSONObject data = new JSONObject();
//                        JSONObject header = new JSONObject();
//                        JSONObject body = new JSONObject();
//                        header.put("Code","1004");
//                        header.put("Time", System.currentTimeMillis());
//                        header.put("Sign","lvzaina");
//                        data.put("Header",header);
//                        body.put("Delay",3);
//                        body.put("Cmd","RemoteOpenDoor");
//                        body.put("MsgId",1682220193);
//                        body.put("Lock",189);
//                        body.put("Type",0);
//                        body.put("ID",0);
//                        data.put("Body",body);
//                        mqttConfigService.publish("topic/receive/"+device.getDeviceCode(),data.toJSONString());
//                        QsgDeviceTask task = new QsgDeviceTask();
//                        task.setUpdateReason("新设备小程序点开门");
//                        task.setUpdateTime(new Date());
//                        task.setEndTime(new Date());
//                        task.setDeviceId(deviceId);
//                        task.setCreateDatetime(new Date());
//                        task.setStatus(1);
//                        task.setDeviceCode(device.getDeviceCode());
//                        task.setTaskType(TaskType.GUANGZHOU_DEVICE_OPEN_DOOR.getValue());
//                        task.setMemberId(currentMember.getId().intValue());
//                        taskService.save(task);
//                    }
                    continue;
                } catch (Exception e) {
                    e.printStackTrace();
                    return new CommonResult().failed();
                }
            }
            //生成开门任务
            order.setOpenStatus(1);
            orderService.updateById(order);
            QsgDeviceTask openDoorTask = new QsgDeviceTask();
            openDoorTask.setCreateDatetime(now);
            openDoorTask.setDeviceCode(device.getDeviceCode());
            openDoorTask.setDeviceId(device.getId());
            openDoorTask.setTaskType(TaskType.OPEN_DOOR_BAOXIANG.getValue());
            openDoorTask.setEndTime(new Date());
            //查询是否存在未执行开门任务的订单
            QueryWrapper qw = new QueryWrapper();
            qw.eq("task_type", TaskType.OPEN_DOOR_BAOXIANG.getValue());
            qw.eq("device_id", device.getId());
            qw.eq("status", 0);
            List<QsgDeviceTask> results = taskService.list(qw);
            //删除掉未执行的开门任务
            if (null != results && results.size() > 0) {
                for (QsgDeviceTask task : results) {
                    taskService.removeById(task.getId());
                }
            }
            openDoorTask.setUpdateTime(new Date());
            openDoorTask.setUpdateReason("订单操作点击的开门任务");
            taskService.save(openDoorTask);
            //查询是否存在有关门任务
            QueryWrapper closerQw = new QueryWrapper();
            closerQw.eq("task_type", TaskType.CLOSE_DOOR.getValue());
            closerQw.eq("device_id", device.getId());
            closerQw.eq("status", 0);
            List<QsgDeviceTask> closeRes = taskService.list(closerQw);
            //删除掉未执行的关门任务，1 只会在后台点关门时生成
            if (null != closeRes && closeRes.size() > 0) {
                for (QsgDeviceTask task : closeRes) {
                    taskService.removeById(task.getId());
                }
            }
            //查询该笔订单是否存在时间任务
            QueryWrapper timeQw = new QueryWrapper();
            timeQw.eq("order_sn", order.getOrderSn());
            timeQw.eq("device_id", device.getId());
            List<QsgDeviceTask> tasks = taskService.list(timeQw);
            if (null == tasks || tasks.size() == 0) {
                //没有该笔订单生成的时间任务，则生成
                QsgDeviceTask timeTask = new QsgDeviceTask();
                timeTask.setUpdateReason("订单操作点击开门生成");
                timeTask.setUpdateTime(new Date());
                timeTask.setMemberId(currentMember.getId().intValue());
                timeTask.setCreateDatetime(new Date());
                timeTask.setDeviceId(deviceId);
                timeTask.setDeviceCode(device.getDeviceCode());
                timeTask.setOrderSn(order.getOrderSn());
                String endTime = order.getEndTime();
                Date date = new Date(endTime);
                timeTask.setEndTime(date);
                timeTask.setTaskType(TaskType.END_REPORT.getValue());
                taskService.save(timeTask);//结束任务
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                calendar.add(Calendar.MINUTE, -5);
                timeTask.setEndTime(calendar.getTime());
                timeTask.setTaskType(TaskType.FIVE_REPORT.getValue());
                taskService.save(timeTask);//结束前5分钟
                calendar.add(Calendar.MINUTE, -25);
                timeTask.setEndTime(calendar.getTime());
                timeTask.setTaskType(TaskType.THIRD_REPORT.getValue());
                taskService.save(timeTask);
            }
            QueryWrapper roomQw = new QueryWrapper();
            roomQw.eq("device_id", device.getId());
            QsgRoom room = roomService.getOne(roomQw);
            if (room.getStatus() != RoomStatus.USRING.getValue()) {//将订单对应房间状态改为使用中
                room.setStatus(RoomStatus.USRING.getValue());
                room.setBeforeStatus(RoomStatus.USRING.getValue());
                roomService.updateById(room);
            }
        }
        return new CommonResult().success();
    }

    @IgnoreAuth
    @GetMapping(value = "/task/generateDamenTask")
    @ApiOperation(value = "生成大门任务")
    public Object generateDamenTask(@RequestParam(required = false) Long orderId) {

        UmsMember currentMember = UserUtils.getCurrentMember();
        List<DmsOrder> orders = null;
        if (null == orderId) {
            //首页点击开大门
            QueryWrapper qw = new QueryWrapper();
            qw.eq("member_id", currentMember.getId());
            qw.eq("order_status", 2);
            qw.select("DISTINCT store_id");
            orders = orderService.list(qw);
            if (null == orders || orders.size() <= 0) {
                return new CommonResult().success(1);
            }
        } else {
            DmsOrder order = orderService.getById(orderId);
            orders = new ArrayList<>();
            orders.add(order);
        }
        for (DmsOrder order : orders) {
            QsgDeviceTask task = new QsgDeviceTask();
            task.setCreateDatetime(new Date());
            task.setEndTime(new Date());
            task.setTaskType(TaskType.OPEN_DOOR_BAOXIANG.getValue());
            //获取大门设备
            QueryWrapper qw = new QueryWrapper();
            qw.eq("store_id", order.getStoreId());
            qw.eq("is_mealdevice", 1);
            List<QsgDevice> devices = deviceService.list(qw);
            if (null != devices && devices.size() > 0) {
                for (QsgDevice damen : devices) {
                    if (damen.getDeviceType() == 1) {
                        //新设备
                        try {
                            JSONObject data = new JSONObject();
                            JSONObject header = new JSONObject();
                            JSONObject body = new JSONObject();
                            header.put("Code", "1004");
                            header.put("Time", System.currentTimeMillis());
                            header.put("Sign", "lvzaina");
                            data.put("Header", header);
                            body.put("Delay", 3);
                            body.put("Cmd", "RemoteOpenDoor");
                            body.put("MsgId", 1682220193);
                            body.put("Lock", 189);
                            body.put("Type", 0);
                            body.put("ID", 0);
                            data.put("Body", body);
                            mqttConfigService.publish("topic/receive/" + damen.getDeviceCode(), data.toJSONString());
                            continue;
                        } catch (Exception e) {
                            e.printStackTrace();
                            return new CommonResult().failed();
                        }
                    }
                    task.setDeviceId(damen.getId());
                    task.setDeviceCode(damen.getDeviceCode());
                    QueryWrapper queryWrapper = new QueryWrapper();
                    queryWrapper.eq("task_type", TaskType.OPEN_DOOR_BAOXIANG.getValue());
                    queryWrapper.eq("device_code", task.getDeviceCode());
                    queryWrapper.eq("status", 0);
                    QsgDeviceTask task1 = taskService.getOne(queryWrapper);
                    if (null == task1) {
                        taskService.save(task);
                    }
                }
            }
        }
        return new CommonResult().success();
    }

    @IgnoreAuth
    @GetMapping(value = "/task/generateDamenTaskForDandian")
    @ApiOperation(value = "生成单店大门任务")
    public Object generateDamenTaskForDandian(Long storeId) {
        QsgDeviceTask task = new QsgDeviceTask();
        task.setCreateDatetime(new Date());
        task.setEndTime(new Date());
        task.setTaskType(TaskType.OPEN_DOOR_BAOXIANG.getValue());
        //获取大门设备
        QueryWrapper qw = new QueryWrapper();
        qw.eq("store_id", storeId);
        qw.eq("is_mealdevice", 1);
        List<QsgDevice> devices = deviceService.list(qw);
        if (null != devices && devices.size() > 0) {
            for (QsgDevice damen : devices) {
                task.setDeviceId(damen.getId());
                task.setDeviceCode(damen.getDeviceCode());
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("task_type", TaskType.OPEN_DOOR_BAOXIANG.getValue());
                queryWrapper.eq("device_code", task.getDeviceCode());
                queryWrapper.eq("status", 0);
                QsgDeviceTask task1 = taskService.getOne(queryWrapper);
                if (null == task1) {
                    taskService.save(task);
                }
            }
        }
        return new CommonResult().success();
    }

    @IgnoreAuth
    @GetMapping(value = "/task/openDamenByUniapp")
    @ApiOperation(value = "生成任务")
    public Object openDamenByUniapp(Long memberId) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("member_id", memberId);
        qw.eq("order_status", OrderStatus.HAS_PAYMONEY.getValue());
        qw.orderByAsc("start_time");
        List<DmsOrder> orders = orderService.list(qw);
        if (null != orders && orders.size() > 0) {
            QueryWrapper qw1 = new QueryWrapper();
            qw1.eq("store_id", orders.get(0).getStoreId());
            qw1.eq("is_mealdevice", 1);
            List<QsgDevice> devices = deviceService.list(qw1);
            if (null == devices || devices.size() <= 0) {
                return new CommonResult().success(1);
            }
            for (QsgDevice damen : devices) {
                QsgDeviceTask task = new QsgDeviceTask();
                task.setDeviceId(damen.getId());
                task.setDeviceCode(damen.getDeviceCode());
                task.setCreateDatetime(new Date());
                task.setEndTime(new Date());
                task.setTaskType(TaskType.OPEN_DOOR_BAOXIANG.getValue());
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("task_type", TaskType.OPEN_DOOR_BAOXIANG.getValue());
                queryWrapper.eq("device_code", task.getDeviceCode());
                queryWrapper.eq("status", 0);
                QsgDeviceTask task1 = taskService.getOne(queryWrapper);
                if (null == task1) {
                    taskService.save(task);
                    return new CommonResult().success(0);
                }
            }
        }
        return new CommonResult().success(1);
    }

    @IgnoreAuth
    @PostMapping(value = "/task/openDamen")
    @ApiOperation(value = "生成任务")
    public Object generateTask(@RequestBody QsgStore store) {
        QsgDeviceTask task = new QsgDeviceTask();
        task.setCreateDatetime(new Date());
        task.setEndTime(new Date());
        task.setTaskType(TaskType.OPEN_DOOR_BAOXIANG.getValue());
        //获取大门设备
        QueryWrapper qw = new QueryWrapper();
        qw.eq("store_id", store.getId());
        qw.eq("is_mealdevice", 1);
        List<QsgDevice> devices = deviceService.list(qw);
        if (null != devices && devices.size() > 0) {
            QsgDevice damen = devices.get(0);
            task.setDeviceId(damen.getId());
            task.setDeviceCode(damen.getDeviceCode());
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("task_type", TaskType.OPEN_DOOR_BAOXIANG.getValue());
        queryWrapper.eq("device_code", task.getDeviceCode());
        queryWrapper.eq("status", 0);
        QsgDeviceTask task1 = taskService.getOne(queryWrapper);
        if (null == task1) {
            taskService.save(task);
        }
        return new CommonResult().success();
    }

    @IgnoreAuth
    @GetMapping(value = "/task/getMealByDuration")
    @ApiOperation(value = "生成任务")
    public Object getMealByDuration(Long orderId, int duration) {
        DmsOrder order = orderService.getById(orderId);
        Long deviceId = order.getDeviceId();
        Long storeId = order.getStoreId().longValue();
        QsgMeal meal = null;
        QsgDevice device = deviceService.getById(deviceId);
        String mealIds = device.getMealId();
        if (StringUtils.isNotBlank(mealIds)) {
            String[] mealId = StringUtils.split(mealIds, ",");
            for (String id : mealId) {
                meal = mealService.getById(Long.valueOf(id));
                if (meal.getIsSale() == 0 && meal.getDuration() == duration) {
                    return new CommonResult().success(meal);
                }
            }
        }
        return new CommonResult().success(0);
    }

    private void operateGatewayDeivce(QsgGatewayDevice gatewayDevice, QsgGatewayInfo gatewayInfo, int type) throws Exception {
        JSONObject data = new JSONObject();
        data.put("CommandId", UUID.randomUUID().toString());
        data.put("SystemCode", "csqsg");
        data.put("GatewayIeee", gatewayInfo.getSerialno());
        data.put("SensorIeee", gatewayDevice.getIeeeEpAddr());
        if (type == 0) {
            data.put("Command", "On");
        } else {
            data.put("Command", "Off");
        }
        mqttConfigService.publish("/toGW/" + gatewayInfo.getMacAddr(), data.toJSONString());
        log.info("发送mqtt消息给设备:{}成功.", gatewayDevice.getIeeeEpAddr());
    }

    private void sendWifiLockMsg(QsgDevice device) {
        HttpClientUtil clientUtil = HttpClientUtil.getInstance();
        Map<String, String> params = new HashMap<>();
        Map<String, String> headMap = new HashMap<>();
        //deviceId为wifi锁的编号
        params.put("deviceId", device.getDeviceCode());
        headMap.put("Authorization", device.getToken());
        String u = clientUtil.httpPost(LockInfo.OPEN_DOOR, params, headMap);
        JSONObject result = JSON.parseObject(u);
        if (200 == result.getIntValue("code")) {
            log.info("打开wifi锁:{}成功.", device.getDeviceCode());
        }
    }

    /**
     * 后台临时开门，不产生断电任务
     *
     * @return
     */
    @IgnoreAuth
    @GetMapping(value = "/task/openDoorTmp")
    @ApiOperation(value = "后台临时开门")
    public Object openDoorTmp(Long deviceId) {
        QsgDevice device = deviceService.getById(deviceId);
        if (device.getDeviceType() == 0) {
            QsgDeviceTask task = new QsgDeviceTask();
            task.setMemberId(1);
            //开门任务
            task.setTaskType(TaskType.OPEN_DOOR_BAOXIANG.getValue());
            task.setDeviceId(deviceId);
            task.setCreateDatetime(new Date());
            task.setDeviceCode(device.getDeviceCode());
            task.setEndTime(new Date());
            QueryWrapper openWrapper = new QueryWrapper();
            openWrapper.eq("device_code", task.getDeviceCode());
            List<Integer> statues = new ArrayList<>();
            statues.add(TaskType.OPEN_DOOR_BAOXIANG.getValue());
            statues.add(TaskType.CLEAR_OPEN.getValue());
            openWrapper.in("task_type", statues);
            openWrapper.eq("status", 0);
            if (null == taskService.getOne(openWrapper)) {
                task.setUpdateTime(new Date());
                task.setUpdateReason("后台点击临时开门生成的任务");
                taskService.save(task);
            }
        } else {
            try {
                JSONObject data1 = new JSONObject();
                JSONObject header1 = new JSONObject();
                JSONObject body1 = new JSONObject();
                header1.put("Code", "1004");
                header1.put("Time", System.currentTimeMillis());
                header1.put("Sign", "lvzaina");
                data1.put("Header", header1);
                body1.put("Delay", 3);
                body1.put("Cmd", "RemoteOpenDoor");
                body1.put("MsgId", 1682220193);
                body1.put("Lock", 189);
                body1.put("Type", 0);
                body1.put("ID", 0);
                data1.put("Body", body1);
                mqttConfigService.publish("topic/receive/" + device.getDeviceCode(), data1.toJSONString());
                QsgDeviceTask task = new QsgDeviceTask();
                task.setMemberId(1);
                //广州设备后台点开门任务
                task.setTaskType(TaskType.GUANGZHOU_OPEN_DOOR.getValue());
                task.setStatus(1);
                task.setDeviceId(deviceId);
                task.setCreateDatetime(new Date());
                task.setDeviceCode(device.getDeviceCode());
                task.setEndTime(new Date());
                task.setUpdateTime(new Date());
                task.setUpdateReason("广州设备后台点开门生成");
                taskService.save(task);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new CommonResult().success();
    }

    /**
     * 后台直接开门
     *
     * @return
     */
    @IgnoreAuth
    @GetMapping(value = "/task/openDoor")
    @ApiOperation(value = "后台直接开门")
    public Object openDoor(Long deviceId) {
        QsgDevice device = deviceService.getById(deviceId);

        String now = DateUtil.dateToString(new Date(), "yyyy/MM/dd HH:mm:ss");
        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.le("start_time", now);
        queryWrapper1.ge("end_time", now);
        queryWrapper1.eq("device_id", device.getId());
        queryWrapper1.eq("order_status", OrderStatus.HAS_PAYMONEY.getValue());
        queryWrapper1.orderByAsc("start_time");
        List<DmsOrder> orders = orderService.list(queryWrapper1);//当前进行的订单
        if (null != orders && orders.size() > 0) {
            //存在正在进行的订单,不给点
            return new CommonResult().success(1);
        }
        if (device.getDeviceType() == 0) {
            QsgDeviceTask task = new QsgDeviceTask();
            task.setMemberId(1);
            //开门任务
            if (StringUtils.isNotBlank(device.getServerIp()) && StringUtils.isNotBlank(device.getServerPort())) {
                task.setTaskType(TaskType.CLEAR_OPEN.getValue());
            } else {
                task.setTaskType(TaskType.OPEN_DOOR_BAOXIANG.getValue());
            }
            task.setDeviceId(deviceId);
            task.setCreateDatetime(new Date());
            task.setDeviceCode(device.getDeviceCode());
            task.setEndTime(new Date());
            QueryWrapper openWrapper = new QueryWrapper();
            openWrapper.eq("device_code", task.getDeviceCode());
            List<Integer> statues = new ArrayList<>();
            statues.add(TaskType.OPEN_DOOR_BAOXIANG.getValue());
            statues.add(TaskType.CLEAR_OPEN.getValue());
            openWrapper.in("task_type", statues);
            openWrapper.eq("status", 0);
            if (null == taskService.getOne(openWrapper)) {
                task.setUpdateReason("后台点保洁开门生成");
                task.setUpdateTime(new Date());
                taskService.save(task);
            }
            if (StringUtils.isNotBlank(device.getServerIp()) && StringUtils.isNotBlank(device.getServerPort())) {
                task.setTaskType(TaskType.CLEAR_CLOSE.getValue());
            } else {
                task.setTaskType(TaskType.END_REPORT.getValue());
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.MINUTE, 15);
            task.setEndTime(calendar.getTime());
            task.setOrderSn("houtai");
            task.setUpdateTime(new Date());
            task.setUpdateReason("后台点击保洁开门生成的15分钟关门");
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("order_sn", "houtai");
            queryWrapper.in("task_type", statues);
            queryWrapper.eq("device_code", task.getDeviceCode());
            queryWrapper.eq("status", 0);
            QsgDeviceTask task1 = taskService.getOne(queryWrapper);
            if (null == task1) {
                taskService.save(task);
            } else {
                taskService.removeById(task1.getId());
                taskService.save(task);
            }
        } else {
            try {
                JSONObject data1 = new JSONObject();
                JSONObject header1 = new JSONObject();
                JSONObject body1 = new JSONObject();
                header1.put("Code", "1004");
                header1.put("Time", System.currentTimeMillis());
                header1.put("Sign", "lvzaina");
                data1.put("Header", header1);
                body1.put("Delay", 15 * 60);
                body1.put("Cmd", "Order");
                body1.put("MsgId", 1683557943);
                body1.put("Lock", 0);
                body1.put("Type", 0);
                body1.put("ID", 0);
                JSONArray node = new JSONArray();
                node.add(1);
                node.add(2);
                body1.put("Node", node);
                data1.put("Body", body1);
                mqttConfigService.publish("topic/receive/" + device.getDeviceCode(), data1.toJSONString());
                QsgDeviceTask task = new QsgDeviceTask();
                task.setStatus(1);
                task.setDeviceCode(device.getDeviceCode());
                task.setMemberId(1);
                task.setTaskType(TaskType.GUANGZHOU_BAOJIE_OPEN_DOOR.getValue());
                task.setDeviceId(deviceId);
                task.setEndTime(new Date());
                task.setCreateDatetime(new Date());
                task.setUpdateReason("广州设备后台直接点保洁开门生成");
                task.setUpdateTime(new Date());
                taskService.save(task);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new CommonResult().success();
    }

    @IgnoreAuth
    @GetMapping(value = "/task/closeDoor")
    @ApiOperation(value = "后台直接关门")
    public Object closeDoor(Long deviceId) {
        QsgDevice device = deviceService.getById(deviceId);
        if (device.getDeviceType() == 0) {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("device_code", device.getDeviceCode());
            queryWrapper.eq("status", 0);
            queryWrapper.eq("member_id", 1);
            List<QsgDeviceTask> tasks = taskService.list(queryWrapper);
            if (null != tasks && tasks.size() > 0) {
                for (QsgDeviceTask task : tasks) {
                    taskService.removeById(task.getId());
                }
            }
            QsgDeviceTask task = new QsgDeviceTask();
            task.setStatus(0);
            task.setDeviceCode(device.getDeviceCode());
            task.setMemberId(1);
            task.setTaskType(TaskType.CLOSE_DOOR.getValue());
            task.setDeviceId(deviceId);
            task.setEndTime(new Date());
            task.setCreateDatetime(new Date());
            task.setUpdateReason("后台直接点击关电生成");
            task.setUpdateTime(new Date());
            taskService.save(task);
        } else if (device.getDeviceType() == 1) {
            try {
                JSONObject data1 = new JSONObject();
                JSONObject header1 = new JSONObject();
                JSONObject body1 = new JSONObject();
                header1.put("Code", "1004");
                header1.put("Time", System.currentTimeMillis());
                header1.put("Sign", "lvzaina");
                data1.put("Header", header1);
                body1.put("Delay", 0);
                body1.put("Cmd", "Order");
                body1.put("MsgId", 1683557943);
                body1.put("Lock", 0);
                body1.put("Type", 0);
                body1.put("ID", 0);
                JSONArray node = new JSONArray();
                node.add(1);
                node.add(2);
                body1.put("Node", node);
                data1.put("Body", body1);
                mqttConfigService.publish("topic/receive/" + device.getDeviceCode(), data1.toJSONString());
                QsgDeviceTask task = new QsgDeviceTask();
                task.setStatus(1);
                task.setDeviceCode(device.getDeviceCode());
                task.setMemberId(1);
                task.setTaskType(TaskType.GUANGZHOU_CLOSE_DOOR.getValue());
                task.setDeviceId(deviceId);
                task.setEndTime(new Date());
                task.setCreateDatetime(new Date());
                task.setUpdateReason("广州设备后台直接点关门生成");
                task.setUpdateTime(new Date());
                taskService.save(task);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new CommonResult().success();
    }
}
